package imessage

import (
	"fmt"
	"github.com/timehop/apns"
)

var apns_conn apns.Client

func PushNotify(deviceId string, msg *Message) error {
	if apns_conn.Conn == nil {
		gw := GetString("apns", "apns_gateway", apns.ProductionGateway)
		cert := GetString("apns", "apns_cert", "apns.crt")
		key := GetString("apns", "apns_key", "apns.key")
		c, err := apns.NewClientWithFiles(gw, cert, key)
		if err != nil {
			return err
		}
		apns_conn = c
	}

	go func() {
		for f := range apns_conn.FailedNotifs {
			syslog.Println("Notif", f.Notif.ID, "failed with", f.Err.Error())
		}
	}()

	p := apns.NewPayload()
	p.APS.Alert.Body = fmt.Sprintf("来自:%v %v的消息，%v", msg.From, msg.Group, msg.Text)
	badge := 5
	p.APS.Badge = &badge
	p.APS.Sound = "turn_down_for_what.aiff"
	p.APS.ContentAvailable = 1
	//p.SetCustomValue(key, value)
	// p.SetCustomValue("link", "zombo://dot/com")
	// p.SetCustomValue("game", map[string]int{"score": 234})
	m := apns.NewNotification()
	m.Payload = p
	m.DeviceToken = deviceId
	m.Priority = apns.PriorityImmediate
	m.Identifier = Hash(msg.MsgId) // Integer for APNS
	m.ID = msg.MsgId               // ID not sent to Apple – to identify error notifications
	return apns_conn.Send(m)
}
